package com.example.restful.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.restful.common.BaseService;
import com.example.restful.common.MaterialState;
import com.example.restful.domain.Borrow;
import com.example.restful.domain.Material;
import com.example.restful.mapper.BorrowMapper;
import com.example.restful.mapper.MaterialMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MaterialService implements BaseService<Material> {
    @Autowired
    MaterialMapper materialMapper;
    @Autowired
    BorrowMapper borrowMapper;

    @Override
    public List<Material> selectAll() {
        return materialMapper.selectList(null);
    }

    @Override
    public Material selectById(int id) {
        return materialMapper.selectById(id);
    }

    @Override
    public boolean addItem(Material item) {
        return  materialMapper.insert(item) != 0;
    }

    @Override
    public boolean deleteById(int id) {
        // 删除材料前，判断该材料是否借出
        Material material = selectById(id);
        //如果物资已借出或不存在，则删除失败
        if(material == null || material.getState() == MaterialState.LOANED)
            return false;
        // 一并删除借出记录
        List<Borrow> borrowList = borrowMapper.selectList(new QueryWrapper<Borrow>().eq("material_id", id));
        for(Borrow borrow: borrowList){
            borrowMapper.deleteById(borrow);
        }
        return materialMapper.deleteById(id) != 0;
    }

    public boolean updateById(int id, Material material){
        material.setId(id);
        return materialMapper.updateById(material) != 0;
    }
}
